package com.lujianfei.searchlistview.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.ListView;

public class ListViewExt extends ListView implements AbsListView.OnScrollListener {

    private float lastY = 0;
    private float dY = 0;
    private View mSearchlayout;
    public ListViewExt(Context context) {
        super(context);
        init();
    }

    public ListViewExt(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ListViewExt(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        setOnScrollListener(this);
    }


    public void setSearchlayout(View mSearchlayout) {
        this.mSearchlayout = mSearchlayout;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
            final int action = event.getAction();

            float y = event.getY();

            switch (action) {
                case MotionEvent.ACTION_DOWN: {
                    lastY = y - dY;
                }
                    break;
                case MotionEvent.ACTION_MOVE: {
                    dY = y - lastY;
                    if (dY <= (-1) * mSearchlayout.getHeight()) {
                        dY = (-1) * mSearchlayout.getHeight();
                        lastY = y + mSearchlayout.getHeight();
                    }
                    if (dY > 0) {
                        dY = 0;
                        lastY = y;
                    }
                    FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mSearchlayout.getLayoutParams();
                    layoutParams.setMargins(0, (int) (dY), 0, 0);
                    mSearchlayout.setLayoutParams(layoutParams);
                }
                    break;
                case MotionEvent.ACTION_UP:{
                    lastY = y - dY;
                }
                break;
                default:{

                }
                break;
            }
            return super.dispatchTouchEvent(event);
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        if (firstVisibleItem == 0) {
            Log.d("ListView", "##### 滚动到顶部 #####");
        } else if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
            Log.d("ListView", "##### 滚动到底部 ######");
        }
    }
}
